package com.xebest.web.controller.restapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.xebest.api.dto.*;
import com.xebest.api.dto.resdto.XeSysMsgRecordResDTO;
import com.xebest.api.service.XeSysMsgApiService;
import com.xebest.api.util.OpertorLogUtil;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.dto.BaseResponseDTO;
import com.xebest.common.base.pagedto.XePageInfoDto;
import com.xebest.common.enums.logtype.ErpLogTypeEnum;
import com.xebest.common.util.HttpClientUtil;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.config.SmsConfig;
import com.xebest.constant.XeConstans;
import com.xebest.constant.XeErrorCode;
import com.xebest.constant.XeSmsConstans;
import com.xebest.util.DateUtil;
import com.xebest.util.SmsConstants;
import com.xebest.web.form.XeVenCarForm;
import com.xebest.web.form.XeVenCarSendForm;
import com.xebest.web.form.XeVenOrderLogisticsForm;
import com.xebest.web.model.XeVenOrderLogisticsDetail;
import com.xebest.web.service.WeChatVenOrderLogisticsService;
import com.xebest.web.service.XeVenOrderLogisticsService;
import com.xebest.web.service.XeVenOrderService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenOrderLogisticsView;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物流中心
 *
 * @author 袁世林
 */
@RestController
@RequestMapping("restApi/weChatLogistic")
public class WeChatVenLogisticRestApi extends BaseController {

	private Logger log = LoggerFactory.getLogger(WeChatVenLogisticRestApi.class);

	/**
	 * 物流Service
	 */
	@Autowired
	private WeChatVenOrderLogisticsService weChatVenOrderLogisticsService;

	@Autowired
	private XeVenOrderLogisticsService logisticsService;

	@Autowired
	private XeVenOrderService xeVenOrderService;

	@Autowired
	private SmsConfig smsConfig;

	@Autowired
	private XeSysMsgApiService xeSysMsgApiService;// 消消乐发送通知业务类

	/**
	 * 物流单查询
	 *
	 * @author 袁世林
	 */
	@RequestMapping("queryOrderLogisticsList")
	public @ResponseBody WeChatVenLogisticsPageDTO<WeChatVenOrderLogisticsResponseDTO> queryOrderLogisticsList(
			@RequestBody XeVenOrderLogisticsRequestDTO dto) {

		log.info("物流单查询入参: {}", JSON.toJSONString(dto));
		WeChatVenLogisticsPageDTO<WeChatVenOrderLogisticsResponseDTO> pageDTO = null;
		try {
			pageDTO = new WeChatVenLogisticsPageDTO<WeChatVenOrderLogisticsResponseDTO>();
			if (null == dto || StringUtils.isBlank(dto.getUserId())) {
				pageDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return pageDTO;
			}
			XeVenOrderLogisticsForm form = new XeVenOrderLogisticsForm();
			PageHelper.startPage(dto.getXePageDto().getPageNum(), dto.getXePageDto().getPageSize());
			// 1.获取userCode
			form.setUserCode(dto.getUserId());
			form.setSearchContent(dto.getSearchContent());
			// 权限使用
			if (XeConstans._XE_TWO == dto.getAdminFlag()) {
				if (!StringUtils.isEmpty(dto.getRoleIds())) {
					form.setRoleId(dto.getRoleIds().split(","));
				} else {
					form.setRoleId(null);
				}
				form.setAdmin("noAdmin");
			} else {
				form.setAdmin(null);
			}

			form.setStartCreateDate(DateUtil.getFrontMonth(3));

			// 2.查询列表数据
			List<XeVenOrderLogisticsView> orderLogisticsList = this.weChatVenOrderLogisticsService
					.queryOrderLogisticsList(form);

			List<WeChatVenOrderLogisticsResponseDTO> weChatVenOrderLogisticsList = JSONArray
					.parseArray(JSONArray.toJSONString(orderLogisticsList), WeChatVenOrderLogisticsResponseDTO.class);

			XePageInfoDto<WeChatVenOrderLogisticsResponseDTO> pageInfo = new XePageInfoDto<WeChatVenOrderLogisticsResponseDTO>(
					weChatVenOrderLogisticsList);
			pageDTO.setList(weChatVenOrderLogisticsList);
			pageDTO.setXePageInfoDto(pageInfo);
			pageDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
			return pageDTO;

		} catch (Exception e) {

			log.error("物流单查询列表接口异常：{}", e);
			pageDTO.setStatus(XeErrorCode.PORJECT_ERROR);

		}
		return pageDTO;
	}

	/**
	 * 物流进度
	 *
	 * @author 袁世林
	 */
	@RequestMapping("queryOrderLogisticsDetail")
	public @ResponseBody WeChatVenLogisticsPageDTO<WeChatVenOrderLogisticsDetailResponseDTO> queryOrderLogisticsDetail(
			@RequestBody XeVenOrderLogisticsRequestDTO dto) {

		log.info("物流进度 查询入参: {}", JSON.toJSONString(dto));
		WeChatVenLogisticsPageDTO<WeChatVenOrderLogisticsDetailResponseDTO> pageDTO = null;
		try {
			pageDTO = new WeChatVenLogisticsPageDTO();
			if (null == dto || StringUtils.isBlank(dto.getUserId()) || StringUtils.isBlank(dto.getOrderId())) {
				pageDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return pageDTO;
			}
			XeVenOrderLogisticsForm form = new XeVenOrderLogisticsForm();
			// 1.获取userCode
			form.setUserCode(dto.getUserId());
			form.setOrderId(dto.getOrderId());
			// 2.查询列表数据
			List<XeVenOrderLogisticsDetail> orderLogisticsDetailList = this.logisticsService
					.selectLogisticsDetailList(form);
			List<WeChatVenOrderLogisticsDetailResponseDTO> weChatVenOrderLogisticsDetailList = JSONArray.parseArray(
					JSONArray.toJSONString(orderLogisticsDetailList), WeChatVenOrderLogisticsDetailResponseDTO.class);

			XePageInfoDto<WeChatVenOrderLogisticsDetailResponseDTO> pageInfo = new XePageInfoDto(
					weChatVenOrderLogisticsDetailList);
			pageDTO.setList(weChatVenOrderLogisticsDetailList);
			pageDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);

			return pageDTO;

		} catch (Exception e) {

			log.error("物流进度 接口异常：{}", e);
			pageDTO.setStatus(XeErrorCode.PORJECT_ERROR);

		}
		return pageDTO;
	}

	/**
	 * 商品信息
	 *
	 * @author 袁世林
	 */
	@RequestMapping("queryGoodsLogisticsDetail")
	public @ResponseBody WeChatVenLogisticsPageDTO<WeChatVenOrderInfoDetailResponseDTO> queryGoodsLogisticsDetail(
			@RequestBody XeVenOrderLogisticsRequestDTO dto) {

		log.info("商品信息 查询入参: {}", JSON.toJSONString(dto));
		WeChatVenLogisticsPageDTO<WeChatVenOrderInfoDetailResponseDTO> pageDTO = new WeChatVenLogisticsPageDTO();
		try {
			if (null == dto || StringUtils.isBlank(dto.getUserId()) || StringUtils.isBlank(dto.getOrderId())) {
				pageDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return pageDTO;
			}
			// 1.获取userCode
			ErpUserInfo userInfo = new ErpUserInfo();
			userInfo.setUserCode(dto.getUserId());
			// 2.查询列表数据
			Map<String, Object> orderDetail = this.xeVenOrderService.queryOrderInfoDetail(dto.getOrderId(), userInfo);
			Object object = orderDetail.get("orderInfoDetail");

			List<WeChatVenOrderInfoDetailResponseDTO> detailList = JSONArray.parseArray(JSONArray.toJSONString(object),
					WeChatVenOrderInfoDetailResponseDTO.class);
			pageDTO.setList(detailList);
			pageDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);

			return pageDTO;

		} catch (Exception e) {

			log.error("商品信息查询 接口异常：{}", e);
			pageDTO.setStatus(XeErrorCode.PORJECT_ERROR);

		}
		return pageDTO;
	}

	/**
	 * 备注信息
	 *
	 * @author 袁世林
	 */
	@RequestMapping("queryRemarkLogisticsDetail")
	public @ResponseBody WeChatVenRemarkLogisticsResponseDTO queryRemarkLogisticsDetail(
			@RequestBody XeVenOrderLogisticsRequestDTO dto) {

		log.info("备注信息 查询入参: {}", JSON.toJSONString(dto));
		WeChatVenRemarkLogisticsResponseDTO responseDto = new WeChatVenRemarkLogisticsResponseDTO();
		try {
			if (null == dto || StringUtils.isBlank(dto.getUserId()) || StringUtils.isBlank(dto.getLogtsCode())) {
				responseDto.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return responseDto;
			}
			XeVenOrderLogisticsForm form = new XeVenOrderLogisticsForm();
			form.setUserCode(dto.getUserId());
			form.setLogtsCode(dto.getLogtsCode());
			// 2.查询列表数据
			Map<String, Object> remarkLogisticsDetail = this.logisticsService.queryRemarkLogisticsDetail(form);

			responseDto = JSONObject.parseObject(JSONObject.toJSONString(remarkLogisticsDetail),
					WeChatVenRemarkLogisticsResponseDTO.class);

			return responseDto;

		} catch (Exception e) {

			log.error("备注信息查询 接口异常：{}", e);
			responseDto.setStatus(XeErrorCode.PORJECT_ERROR);
		}
		return responseDto;
	}

	/**
	 * 物流派车列表查询
	 *
	 * @author 袁世林
	 */
	@RequestMapping("querySendCarList")
	public @ResponseBody WeChatVenLogisticsPageDTO<WeChatVenOrderLogisticsResponseDTO> querySendCarList(
			@RequestBody XeVenOrderLogisticsRequestDTO dto) {

		log.info("物流派车列表查询入参: {}", JSON.toJSONString(dto));
		WeChatVenLogisticsPageDTO<WeChatVenOrderLogisticsResponseDTO> pageDTO = null;
		try {
			pageDTO = new WeChatVenLogisticsPageDTO<WeChatVenOrderLogisticsResponseDTO>();
			if (null == dto || StringUtils.isBlank(dto.getUserId())) {
				pageDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return pageDTO;
			}
			XeVenOrderLogisticsForm form = new XeVenOrderLogisticsForm();
			PageHelper.startPage(dto.getXePageDto().getPageNum(), dto.getXePageDto().getPageSize());
			// 1.获取userCode
			form.setUserCode(dto.getUserId());
			form.setSearchContent(dto.getSearchContent());
			// 权限使用
			if (XeConstans._XE_TWO == dto.getAdminFlag()) {
				if (!StringUtils.isEmpty(dto.getRoleIds())) {
					form.setRoleId(dto.getRoleIds().split(","));
				} else {
					form.setRoleId(null);
				}
				form.setAdmin("noAdmin");
			} else {
				form.setAdmin(null);
			}
			// 2.查询列表数据
			List<XeVenOrderLogisticsView> sendCarList = this.weChatVenOrderLogisticsService.querySendCarList(form);

			List<WeChatVenOrderLogisticsResponseDTO> weChatVenOrderLogisticsList = JSONArray
					.parseArray(JSONArray.toJSONString(sendCarList), WeChatVenOrderLogisticsResponseDTO.class);

			XePageInfoDto<WeChatVenOrderLogisticsResponseDTO> pageInfo = new XePageInfoDto<WeChatVenOrderLogisticsResponseDTO>(
					weChatVenOrderLogisticsList);
			pageDTO.setList(weChatVenOrderLogisticsList);
			pageDTO.setXePageInfoDto(pageInfo);
			pageDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);

			return pageDTO;

		} catch (Exception e) {

			log.error("物流派车列表接口异常：{}", e);
			pageDTO.setStatus(XeErrorCode.PORJECT_ERROR);
		}
		return pageDTO;
	}

	/**
	 * 跳转到派车页面
	 *
	 * @author 袁世林
	 */
	@RequestMapping("toSendCarPage")
	public @ResponseBody WeChatVenSendCarPageDTO toSendCarPage(@RequestBody XeVenOrderLogisticsRequestDTO dto) {

		WeChatVenSendCarPageDTO responseDto = new WeChatVenSendCarPageDTO();
		try {
			// 1.验证参数
			if (null == dto || StringUtils.isBlank(dto.getUserId()) || StringUtils.isBlank(dto.getLogtsCode())) {
				responseDto.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return responseDto;
			}

			XeVenOrderLogisticsForm form = new XeVenOrderLogisticsForm();
			form.setUserCode(dto.getUserId());
			form.setLogtsCode(dto.getLogtsCode());
			// 2.查询列表数据
			Map<String, Object> sendCarLogistics = this.logisticsService.querySendCarLogisticsByLogtsCode(form);
			// 返回的默认车辆信息
			Map<String, Object> latelySendCar = new HashMap<String, Object>();
			if (null != sendCarLogistics && !StringUtils.isEmpty((String) sendCarLogistics.get("shipCarDes"))) {
				if (!StringUtils.isEmpty((String) sendCarLogistics.get("shipCarId"))) {
					latelySendCar = logisticsService
							.queryCarInfoByCarId(Integer.valueOf(sendCarLogistics.get("shipCarId").toString()));
				}
				// 4.返回信息

				responseDto.setSendCarLogistics(sendCarLogistics);
				responseDto.setLatelySendCar(latelySendCar);
				responseDto.setStatus(XeErrorCode.PORJECT_SUCCESS);
				return responseDto;
			} else {
				// 3.获取派车页所需数据根据发货，收货区域，usercode获取最近一张物流单的未删除承运车辆
				Map<String, Object> paraMap = new HashMap<String, Object>();
				paraMap.put("userCode", dto.getUserId());
				paraMap.put("caProvinceId", sendCarLogistics.get("caProvinceId"));
				paraMap.put("caCityId", sendCarLogistics.get("caCityId"));
				paraMap.put("caAreaId", sendCarLogistics.get("caAreaId"));
				paraMap.put("provinceId", sendCarLogistics.get("provinceId"));
				paraMap.put("cityId", sendCarLogistics.get("cityId"));
				paraMap.put("areaId", sendCarLogistics.get("areaId"));
				latelySendCar = this.logisticsService.querylatelySendCarLogistics(paraMap);

				// 4.返回信息

				responseDto.setSendCarLogistics(sendCarLogistics);
				responseDto.setLatelySendCar(latelySendCar);
				responseDto.setStatus(XeErrorCode.PORJECT_SUCCESS);
				return responseDto;
			}
		} catch (Exception e) {
			log.error("跳转到派车页面接口异常：{}", e);
			responseDto.setStatus(XeErrorCode.PORJECT_ERROR);
			return responseDto;
		}

	}

	/**
	 * 查询车辆信息
	 *
	 * @author 袁世林
	 */
	@RequestMapping("queryCarList")
	public @ResponseBody WeChatVenLogisticsPageDTO<Map<String, Object>> queryCarList(
			@RequestBody XeVenOrderLogisticsRequestDTO dto) {

		log.info("查询车辆信息入参: {}", JSON.toJSONString(dto));
		WeChatVenLogisticsPageDTO<Map<String, Object>> pageDTO = new WeChatVenLogisticsPageDTO();
		try {
			if (null == dto || StringUtils.isBlank(dto.getLogtsCode())) {
				pageDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return pageDTO;
			}

			String dtoJson = JSONObject.toJSONString(dto);
			// 查询条件封装
			XeVenOrderLogisticsForm form = JSONObject.parseObject(dtoJson, XeVenOrderLogisticsForm.class);

			// 2.查询列表数据
			List<Map<String, Object>> sendCarLogisticsList = new ArrayList<Map<String, Object>>();

			if (StringUtils.isNotBlank(dto.getSearchContent())) {
				XePageInfoDto<Map<String, Object>> pageInfo = new XePageInfoDto<>(sendCarLogisticsList);
				PageHelper.startPage(dto.getXePageDto().getPageNum(), dto.getXePageDto().getPageSize());
				sendCarLogisticsList = this.weChatVenOrderLogisticsService.queryAllCarList(form);
				pageInfo = new XePageInfoDto<>(sendCarLogisticsList);

				pageDTO.setXePageInfoDto(pageInfo);

				pageDTO.setList(sendCarLogisticsList);

				pageDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);

				return pageDTO;
			}

			// 查询当前区域的车辆，如果没有返回全部车辆
			PageHelper.startPage(dto.getXePageDto().getPageNum(), dto.getXePageDto().getPageSize());
			sendCarLogisticsList = this.weChatVenOrderLogisticsService.queryCarList(form);
			XePageInfoDto<Map<String, Object>> pageInfo = new XePageInfoDto<>(sendCarLogisticsList);
			if (pageInfo.getTotal() == 0) {
				PageHelper.startPage(dto.getXePageDto().getPageNum(), dto.getXePageDto().getPageSize());
				sendCarLogisticsList = this.weChatVenOrderLogisticsService.queryAllCarList(form);
				pageInfo = new XePageInfoDto<>(sendCarLogisticsList);
			}

			pageDTO.setXePageInfoDto(pageInfo);

			pageDTO.setList(sendCarLogisticsList);

			pageDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);

			return pageDTO;

		} catch (Exception e) {

			log.error("查询车辆信息 接口异常：{}", e);
			pageDTO.setStatus(XeErrorCode.PORJECT_ERROR);

		}
		return pageDTO;
	}

	/**
	 * 装车点，卸货点默认值，及历史记录
	 *
	 * @author 袁世林
	 */
	@RequestMapping("queryCarAddress")
	public @ResponseBody WeChatVenCarAddressResponseDTO queryCarAddress(
			@RequestBody XeVenOrderLogisticsRequestDTO dto) {

		WeChatVenCarAddressResponseDTO responseDto = new WeChatVenCarAddressResponseDTO();

		String paramJson = JSONObject.toJSONString(dto);
		log.info("物流车辆管理列表,传入参数： {}", paramJson);
		try {
			// 1.验证参数

			XeVenCarForm carForm = new XeVenCarForm();
			carForm.setSelAddrFlag(dto.getSelAddrFlag());
			carForm.setCarId(dto.getCarId());
			carForm.setUserCode(dto.getUserId());
			// 2.查询列表数据
			List<Map<String, Object>> carAddressList = new ArrayList<Map<String, Object>>();
			Map<String, Object> carAddress = new HashMap<String, Object>();
			if (carForm.getSelAddrFlag() != null && carForm.getSelAddrFlag() == 1) {// 查询10条装车卸货历史记录
				carAddressList = this.logisticsService.queryCarAddressList(carForm);
			} else {
				carAddress = this.logisticsService.queryCarAddress(carForm);
			}

			responseDto = new WeChatVenCarAddressResponseDTO();

			responseDto.setCarAddressList(carAddressList);
			responseDto.setCarAddress(carAddress);

			responseDto.setStatus(XeErrorCode.PORJECT_SUCCESS);
			return responseDto;

		} catch (Exception e) {
			log.error("装车点，卸货点默认值，及历史记录查询 接口异常：{}", e);
			responseDto.setStatus(XeErrorCode.PORJECT_ERROR);
			return responseDto;
		}

	}

	/**
	 * 保存派车信息
	 *
	 * @author 袁世林
	 */
	@RequestMapping("saveSendCarInfo")
	public @ResponseBody BaseResponseDTO saveSendCarInfo(@RequestBody XeVenCarSendRequestDto dto) {

		BaseResponseDTO responseDTO = new BaseResponseDTO();

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(dto.getLoadAddr()) || StringUtils.isEmpty(dto.getLoadTime())
					|| StringUtils.isEmpty(dto.getUnloadAddr()) || StringUtils.isEmpty(dto.getUnloadTime())
					|| dto.getCarId() == null || StringUtils.isEmpty(dto.getLogtCode()) || dto.getProvinceId() == null
					|| dto.getCityId() == null || dto.getAreaId() == null || dto.getCaProvinceId() == null
					|| dto.getCaCityId() == null || dto.getCaAreaId() == null
					|| StringUtils.isEmpty(dto.getCarPlateNum()) || StringUtils.isEmpty(dto.getMobilePhone())
					|| dto.getUpFlag() == null || dto.getUserCode() == null) {
				responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return responseDTO;
			}
			log.info("保存派车信息:接口传入参数：{}", JSON.toJSONString(dto));
			XeVenCarSendForm form = new XeVenCarSendForm();

			form = JSON.parseObject(JSONObject.toJSONString(dto), XeVenCarSendForm.class);

			form.setUserCode(dto.getUserCode());

			form.setCreateUser(dto.getLoginName());

			// 验证订单状态
			Map<String, Object> orderStateMap = logisticsService.queryOrderStateByLogtCode(form.getLogtCode());
			if (orderStateMap.get("orderStatus").toString().equals("1")
					|| orderStateMap.get("orderStatus").toString().equals("2")) {

				responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);

				return responseDTO;
			} else if (orderStateMap.get("orderStatus").toString().equals("4")) {
				responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return responseDTO;
			}
			// 验证车辆路线
			Map<String, Object> carLinesMap = logisticsService.queryCarLinesByCarId(form.getCarId());
			// 若仓库所在地到收货区域不是承运车辆的承运线路，则新增承运线路
			int res = 0;
			if (null != carLinesMap) {
				String sendArea = form.getProvinceId() + "" + form.getCityId() + "" + form.getAreaId();
				String receiptArea = form.getCaProvinceId() + "" + form.getCaCityId() + "" + form.getCaAreaId();
				if (!((carLinesMap.get("sendArea").toString().contains(sendArea)
						|| carLinesMap.get("sendArea").toString().contains(receiptArea))
						& (carLinesMap.get("receiptArea").toString().contains(sendArea)
								|| carLinesMap.get("receiptArea").toString().contains(receiptArea)))) {
					res = logisticsService.saveCarLines(form);
				}
			} else {
				res = logisticsService.saveCarLines(form);
			}
			// 2.保存数据
			res = this.logisticsService.saveSendCarInfo(form);
			// 派车成功向采购商发送短信
			StringBuffer sb = new StringBuffer();
			sb.append("mobileNO=").append(orderStateMap.get("loginAccount")).append("&merchantKey=")
					.append(smsConfig.getMerchantKey());
			String verifyString = XeBaseUtil.baseUtil.getKeyedDigest(sb.toString(), SmsConstants.MSG_MERCHANT_KEY);
			JSONObject smsJson = new JSONObject();
			smsJson.put("mobileNO", orderStateMap.get("loginAccount"));
			smsJson.put("sendSource", "派车成功向采购商发送短信");
			smsJson.put("smsNO", XeSmsConstans.XE_ERP_SENDCAR_PUR_SEND_MSG);
			smsJson.put("verifyString", verifyString);
			smsJson.put("orderNum", orderStateMap.get("orderId"));
			smsJson.put("carPlateNum", form.getCarPlateNum());
			smsJson.put("contactPerson", form.getContactPerson());
			smsJson.put("mobilePhone", form.getMobilePhone());
			log.info("派车成功向采购商发送短信参数：--->" + JSON.toJSONString(smsJson));
			HttpClientUtil.postJSON(smsConfig.getSmsUrl(), smsJson);
			// 派车成功向消消乐客户经理发送通知
			List<XeSysMsgSendDTO> xeSysMsgSendDTOList = new ArrayList<>();
			XeSysMsgRecordDTO msgRecordDTO = new XeSysMsgRecordDTO();
			XeSysMsgSendDTO sendDTO = new XeSysMsgSendDTO();
			sendDTO.setMsgNumber(XeSmsConstans.XE_ERP_SENDCAR_SALESMAN_SEND_MSG_NOTICE);
			if (!StringUtils.isEmpty((String) orderStateMap.get("salesmanPhone"))) {
				sendDTO.setMobile(orderStateMap.get("salesmanPhone").toString());
			}
			if (!StringUtils.isEmpty(orderStateMap.get("salesmanId").toString())) {
				sendDTO.setUserId(orderStateMap.get("salesmanId").toString());
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("userName", orderStateMap.get("userName") == null ? "" : orderStateMap.get("userName"));
			jsonObject.put("loginAccount", orderStateMap.get("loginAccount"));
			jsonObject.put("orderNum", orderStateMap.get("orderId"));
			jsonObject.put("carNum", form.getCarPlateNum());
			jsonObject.put("linkMan", form.getContactPerson() == null ? "" : form.getContactPerson());
			jsonObject.put("contactNum", form.getMobilePhone());
			sendDTO.setMsgContentParam(jsonObject);
			JSONObject jsonObjectJump = new JSONObject();
			jsonObjectJump.put("subOrderId", orderStateMap.get("orderId"));
			jsonObjectJump.put("userId", orderStateMap.get("userId"));// 业务员标识
			jsonObjectJump.put("orderPlat", orderStateMap.get("orderSource"));
			sendDTO.setJumpData(jsonObjectJump);// 跳转参数设置
			xeSysMsgSendDTOList.add(sendDTO);
			msgRecordDTO.setXeSysMsgSendDTOList(xeSysMsgSendDTOList);
			log.info("派车成功向客户经理消消乐推送通知入参：--->" + JSON.toJSONString(msgRecordDTO));
			XeSysMsgRecordResDTO msgRecordResDTO = xeSysMsgApiService.sendMsgRecords(msgRecordDTO);
			log.info("派车成功向客户经理消消乐推送通知返回结果：--->" + JSON.toJSONString(msgRecordResDTO));

			Map<String, Object> map = new HashMap<String, Object>();
			if (res > 0) {
				// 添加操作日志信息
				OpertorLogUtil.opertorLog.sendOperatorLogByParam(getRequestIP(), null,
						ErpLogTypeEnum.erpFinLogistics.getValue(), dto.getLoginName(),
						"微信生意管家派车。物流单号：" + form.getLogtCode() + "。承运车辆：" + form.getCarPlateNum()
								+ "。装车点：" + form.getLoadAddr() + "。预计装车时间" + form.getLoadTime() + "。卸货点："
								+ form.getUnloadAddr() + "。预计送达时间" + form.getUnloadTime() + "。",
						dto.getUserCode());
				// 3.返回信息
				map.put("info", "派车成功！");
			} else {
				map.put("info", "保存失败，请稍后重试！");
			}

			// 向司机发送短信通知

			String logtsCode = dto.getLogtCode();
			String orderId = (String) orderStateMap.get("orderId");
			String userCode = dto.getUserCode();
			String mobilePhone = dto.getMobilePhone();

			log.info("-----微信生意管家派车向司机发短信通知--------开始");
			weChatVenOrderLogisticsService.sendMsgToDriver(logtsCode, orderId, userCode, mobilePhone);
			log.info("-----微信生意管家派车向司机发短信通知--------结束");
			responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
			return responseDTO;
		} catch (Exception e) {
			log.error("保存派车信息接口异常：{}", e);
			responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
			return responseDTO;
		}

	}
	/**
	 * 保存派车信息
	 *
	 * @author 袁世林
	 */
	@RequestMapping("saveSendExpressInfo")
	public @ResponseBody BaseResponseDTO saveSendExpressInfo(@RequestBody XeVenCarSendRequestDto dto) {

		BaseResponseDTO responseDTO = new BaseResponseDTO();

		try {
			// 1.验证参数
			if (StringUtils.isEmpty(dto.getExpressName()) || StringUtils.isEmpty(dto.getExpressNumber()) || StringUtils.isEmpty(dto.getLogtCode())
					|| dto.getUpFlag() == null || dto.getUserCode() == null) {
				responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return responseDTO;
			}
			log.info("保存派车信息:接口传入参数：{}", JSON.toJSONString(dto));
			XeVenCarSendForm form = new XeVenCarSendForm();

			form = JSON.parseObject(JSONObject.toJSONString(dto), XeVenCarSendForm.class);

			form.setUserCode(dto.getUserCode());

			form.setCreateUser(dto.getLoginName());

			// 验证订单状态
			Map<String, Object> orderStateMap = logisticsService.queryOrderStateByLogtCode(form.getLogtCode());
			if (orderStateMap.get("orderStatus").toString().equals("1")
					|| orderStateMap.get("orderStatus").toString().equals("2")) {

				responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);

				return responseDTO;
			} else if (orderStateMap.get("orderStatus").toString().equals("4")) {
				responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return responseDTO;
			}
			// 若仓库所在地到收货区域不是承运车辆的承运线路，则新增承运线路
			int res = 0;
			// 2.保存数据
			res = this.logisticsService.saveSendCarInfo(form);
			// 派车成功向采购商发送短信
			StringBuffer sb = new StringBuffer();
			sb.append("mobileNO=").append(orderStateMap.get("loginAccount")).append("&merchantKey=")
					.append(smsConfig.getMerchantKey());
			String verifyString = XeBaseUtil.baseUtil.getKeyedDigest(sb.toString(), SmsConstants.MSG_MERCHANT_KEY);
			JSONObject smsJson = new JSONObject();
			smsJson.put("mobileNO", orderStateMap.get("loginAccount"));
			smsJson.put("sendSource", "派车成功向采购商发送短信");
			smsJson.put("smsNO", XeSmsConstans.XE_ERP_SENDCAR_PUR_SEND_MSG);
			smsJson.put("verifyString", verifyString);
			smsJson.put("orderNum", orderStateMap.get("orderId"));
			smsJson.put("carPlateNum", form.getCarPlateNum());
			smsJson.put("contactPerson", form.getContactPerson());
			smsJson.put("mobilePhone", form.getMobilePhone());
			log.info("派车成功向采购商发送短信参数：--->" + JSON.toJSONString(smsJson));
			HttpClientUtil.postJSON(smsConfig.getSmsUrl(), smsJson);
			// 派车成功向消消乐客户经理发送通知
			List<XeSysMsgSendDTO> xeSysMsgSendDTOList = new ArrayList<>();
			XeSysMsgRecordDTO msgRecordDTO = new XeSysMsgRecordDTO();
			XeSysMsgSendDTO sendDTO = new XeSysMsgSendDTO();
			sendDTO.setMsgNumber(XeSmsConstans.XE_ERP_SENDCAR_SALESMAN_SEND_MSG_NOTICE);
			if (!StringUtils.isEmpty((String) orderStateMap.get("salesmanPhone"))) {
				sendDTO.setMobile(orderStateMap.get("salesmanPhone").toString());
			}
			if (!StringUtils.isEmpty(orderStateMap.get("salesmanId").toString())) {
				sendDTO.setUserId(orderStateMap.get("salesmanId").toString());
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("userName", orderStateMap.get("userName") == null ? "" : orderStateMap.get("userName"));
			jsonObject.put("loginAccount", orderStateMap.get("loginAccount"));
			jsonObject.put("orderNum", orderStateMap.get("orderId"));
			jsonObject.put("carNum", form.getCarPlateNum());
			jsonObject.put("linkMan", form.getContactPerson() == null ? "" : form.getContactPerson());
			jsonObject.put("contactNum", form.getMobilePhone());
			sendDTO.setMsgContentParam(jsonObject);
			JSONObject jsonObjectJump = new JSONObject();
			jsonObjectJump.put("subOrderId", orderStateMap.get("orderId"));
			jsonObjectJump.put("userId", orderStateMap.get("userId"));// 业务员标识
			jsonObjectJump.put("orderPlat", orderStateMap.get("orderSource"));
			sendDTO.setJumpData(jsonObjectJump);// 跳转参数设置
			xeSysMsgSendDTOList.add(sendDTO);
			msgRecordDTO.setXeSysMsgSendDTOList(xeSysMsgSendDTOList);
			log.info("派车成功向客户经理消消乐推送通知入参：--->" + JSON.toJSONString(msgRecordDTO));
			XeSysMsgRecordResDTO msgRecordResDTO = xeSysMsgApiService.sendMsgRecords(msgRecordDTO);
			log.info("派车成功向客户经理消消乐推送通知返回结果：--->" + JSON.toJSONString(msgRecordResDTO));

			Map<String, Object> map = new HashMap<String, Object>();
			if (res > 0) {
				// 添加操作日志信息
				OpertorLogUtil.opertorLog.sendOperatorLogByParam(getRequestIP(), null,
						ErpLogTypeEnum.erpFinLogistics.getValue(), dto.getLoginName(),
						"微信生意管家派车。物流单号：" + form.getLogtCode() + "。承运车辆：" + form.getCarPlateNum()
								+ "。装车点：" + form.getLoadAddr() + "。预计装车时间" + form.getLoadTime() + "。卸货点："
								+ form.getUnloadAddr() + "。预计送达时间" + form.getUnloadTime() + "。",
						dto.getUserCode());
				// 3.返回信息
				map.put("info", "派车成功！");
			} else {
				map.put("info", "保存失败，请稍后重试！");
			}

			// 向司机发送短信通知

			String logtsCode = dto.getLogtCode();
			String orderId = (String) orderStateMap.get("orderId");
			String userCode = dto.getUserCode();
			String mobilePhone = dto.getMobilePhone();

			log.info("-----微信生意管家派车向司机发短信通知--------开始");
			weChatVenOrderLogisticsService.sendMsgToDriver(logtsCode, orderId, userCode, mobilePhone);
			log.info("-----微信生意管家派车向司机发短信通知--------结束");
			responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
			return responseDTO;
		} catch (Exception e) {
			log.error("保存派车信息接口异常：{}", e);
			responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
			return responseDTO;
		}

	}

	/**
	 * 物流车辆管理列表
	 *
	 * @author 袁世林
	 */
	@RequestMapping("queryLogisticsCarList")
	public @ResponseBody WeChatVenCarListPageDTO<?> queryLogisticsCarList(
			@RequestBody XeVenOrderLogisticsRequestDTO dto) {

		WeChatVenCarListPageDTO<?> responseDto = new WeChatVenCarListPageDTO();

		String paramJson = JSONObject.toJSONString(dto);
		log.info("物流车辆管理列表,传入参数： {}", paramJson);

		try {

			XeVenOrderLogisticsForm form = new XeVenOrderLogisticsForm();

			form.setSearchContent(dto.getSearchContent());
			form.setUserCode(dto.getUserId());

			responseDto = weChatVenOrderLogisticsService.queryErpLogisticsCarList(form, dto.getXePageDto().getPageNum(),
					dto.getXePageDto().getPageSize());

			responseDto.setStatus(XeErrorCode.PORJECT_SUCCESS);
			return responseDto;

		} catch (Exception e) {
			log.error("物流车辆管理列表 接口异常：{}", e);
			responseDto.setStatus(XeErrorCode.PORJECT_ERROR);
			return responseDto;
		}

	}

	/**
	 * 确认接货
	 *
	 * @author 袁世林
	 */
	@RequestMapping("confirmDelivery")
	public BaseResponseDTO confirmDelivery(@RequestBody XeVenOrderLogisticsRequestDTO dto) {

		String paramJson = JSONObject.toJSONString(dto);
		log.info("确认接货,传入参数： {}", paramJson);
		BaseResponseDTO responseDTO = new BaseResponseDTO();
		try {

			if (StringUtils.isBlank(dto.getLogtsCode())) {
				responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return responseDTO;
			}
			weChatVenOrderLogisticsService.confirmDelivery(dto.getLogtsCode());

			responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);

			// 添加操作日志信息
			OpertorLogUtil.opertorLog.sendOperatorLogByParam(getRequestIP(), null,
					ErpLogTypeEnum.erpFinLogistics.getValue(), dto.getLoginName(),
					"微信生意管家---物流单号: " + dto.getLogtsCode() + "--确认接货成功", dto.getUserId());

			return responseDTO;
		} catch (Exception e) {
			log.error("确认接货 接口异常：{}", e);
			responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
			return responseDTO;
		}

	}

	/**
	 * 司机回复短信后回调通知--自动更新为已接货状态
	 *
	 * @author 袁世林
	 */
	@RequestMapping("replyMsgAfterCallBack")
	public BaseResponseDTO replyMsgAfterCallBack(@RequestBody ReplyMsgCallBackDTO dto) {

		String paramJson = JSONObject.toJSONString(dto);
		log.info("司机回复短信后回调通知传入参数： {}", paramJson);
		BaseResponseDTO responseDTO = new BaseResponseDTO();
		try {
			if (dto == null || dto.getSuccessCallBack() == null || dto.getSuccessCallBack().size() == 0) {
				responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
				return responseDTO;
			}
			for (ReplyMsgCallBackDetailDTO successDto : dto.getSuccessCallBack()) {
				weChatVenOrderLogisticsService.confirmDelivery(successDto.getDealNo());
				log.info("司机回复短信后回调通知后---更新已接货成功----" + successDto.getDealNo());
			}

			responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
			return responseDTO;
		} catch (Exception e) {
			log.error("司机回复短信后回调通知 接口异常：{}", e);
			responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
			return responseDTO;
		}

	}

}
